package way.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import way.client.R;
import way.client.LocationUpdate.MyLocationListenner;
import way.client.LocationUpdate.NotifyLister;
import way.client.LocationUpdate.Updata;
import way.client.MyItemizedOverlay;
import way.sql.JSONParser;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.VersionInfo;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class wayclient extends Activity {
    
	static MapView mMapView = null;
	
	private MapController mMapController = null;

	public MKMapViewListener mMapListener = null;
	FrameLayout mMapViewContainer = null;
	
	private ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();
	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
    public NotifyLister mNotifyer=null;
    private static final String TAG_MESSAGE = "message";
	Button testUpdateButton = null;
	
	EditText getPhoneText = null;
	MyLocationOverlay myLocationOverlay = null;
	int index =0;
	LocationData locData = null;
	
	
	
	//define the urls  
	//static String url_down="http://okoop.my.phpcloud.com/findus/down/down.php";
	//static String url_up="http://okoop.my.phpcloud.com/findus/up/up.php";
	static String sIp="192.168.1.100";
	//static String sIp="10.0.0.2";
	String sDNSName="okoop.vicp.cc";
	static String url_down="http://"+sIp+"/down/down.php";
	static String url_up="http://"+sIp+"/up/up.php";
	static String url_checkusr="http://"+sIp+"/up/checkusr.php";
	
	
	// 存放overlayitem s
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	
	Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(wayclient.this, "i am here!", Toast.LENGTH_SHORT).show();
        };
    };
    public double dUsrLon=0;
    public double dUsrLat=0;
    public String sUsrTime="";
    String sUinfo=""; 
   

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updateloc);
        
        String versionInof = VersionInfo.getApiVersion();
        //mListView = (ListView)findViewById(R.id.listView); 
        // 添加ListItem，设置事件响应
        List<String> data = new ArrayList<String>();
     	for (int i = 0; i < mStrDemos.length; i++) {
     		data.add(mStrDemos[i]);
     	}
     	
     	//Intent intent = null;
     	//intent = new Intent(wayclient.this, mActivities[0]);
     	//this.startActivity(intent);
     	
     	
        mMapView = (MapView)findViewById(R.id.bmapView);
        //getPhoneText=(EditText)findViewById(R.id.phoneNum);//取到号码
        mMapController = mMapView.getController();
        
        initMapView();
        
        mLocClient = new LocationClient( this );
        mLocClient.registerLocationListener( myListener );
        
        //位置提醒相关代码
        mNotifyer = new NotifyLister();
        mNotifyer.SetNotifyLocation(42.0324965,113.3129,3000,"bd09ll");//4个参数代表要位置提醒的点的坐标，具体含义依次为：纬度，经度，距离范围，坐标系类型(gcj02,gps,bd09,bd09ll)
        mLocClient.registerNotify(mNotifyer);
        LocationClientOption option = new LocationClientOption();
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置网络优先 
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.setScanSpan(10000); // //定时定位，每隔5秒钟定位一次
        mLocClient.setLocOption(option);
        
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //String imsi = mTelephonyMgr.getSubscriberId();
        //String imei = mTelephonyMgr.getDeviceId();
        //String IMSI =android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);


        String imei =((TelephonyManager)this.getSystemService(TELEPHONY_SERVICE)).getDeviceId();
        String imsi =((TelephonyManager)this.getSystemService(TELEPHONY_SERVICE)).getSubscriberId();

        //String IMEI =android.os.SystemProperties.get(android.telephony.TelephonyManager.p.telephony.TelephonyProperties.PROPERTY_IMEI)
        WifiManager wifi = (WifiManager)this.getSystemService(Context.WIFI_SERVICE); 
        WifiInfo info = wifi.getConnectionInfo(); 
        String wifiimei = info.getMacAddress();
        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = telephonyManager.getLine1Number();
        String android_id = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
        Log.i("IMSI:", imsi);
        Log.i("IMEI:", imei);//最好拿
        Log.i("phoneNumber:", phoneNumber);
        Log.i("android_id:", android_id);
        Log.i("wifiimei:", wifiimei);//最好拿
        sUinfo=imei+wifiimei;

		
		 /** 
	     * 创建图标资源（用于显示在overlayItem所标记的位置） 
	     */  
	    //Drawable marker = this.getResources().getDrawable(R.drawable.ic_launcher);  
	    // 为maker定义位置和边界   
	    //marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());  

		  /** 
	     * 创建自定义的ItemizedOverlay 
	     */  
	    //final MyItemizedOverlay overlay = new MyItemizedOverlay(marker, this);  
	    //final GeoPoint pt1 = new GeoPoint((int)(47.118440*1E6), (int)(87.493147*1E6));
	    //OverlayItem overlayItem1 = new OverlayItem(pt1, "i", "I AM Here"); 
	    
        mLocClient.registerLocationListener(new BDLocationListener(){

    			@Override
    			public void onReceiveLocation (BDLocation location) {
    				// TODO Auto-generated method stub
    				 if (location == null) 
    	                    return ; 
    	                StringBuffer sb = new StringBuffer(256); 
    	                sb.append("time : "); 
    	                sb.append(location.getTime()); 
    	                
    	                sUsrTime=location.getTime();
    	                sb.append("\nerror code : "); 
    	                sb.append(location.getLocType()); 
    	                sb.append("\nlatitude : "); 
    	                sb.append(location.getLatitude()); 
    	                sb.append("\nlontitude : "); 
    	                sb.append(location.getLongitude()); 
    	                
    	                dUsrLon=location.getLatitude();//get the longitude
    	                dUsrLat=location.getLatitude();//get the latitude
    	                //locData.latitude=dUsrLon;
    	        		//locData.longitude=dUsrLat;
    	        		//myLocationOverlay.setData(locData);        			
    	        		//mMapView.getOverlays().add(myLocationOverlay);
    	        		
    	                //pt1.setLatitudeE6((int)(dUsrLat*1E6));
    	                //pt1.setLongitudeE6((int)(dUsrLon*1E6));
    	        		//
    	                //GeoPoint point1 = new GeoPoint((int)(dUsrLat*1E6),(int)(dUsrLon*1E6));  
    	                //OverlayItem overlayItem1 = new OverlayItem(pt1, "i", "I AM Here");  
    	                // 将标记添加到图层中（可添加多个OverlayItem）   
    	                //overlay.addItem(overlayItem1); 
    	            
    	                locData.latitude = location.getLatitude();
    	                locData.longitude = location.getLongitude();
    	                locData.direction = 2.0f;
    	                locData.accuracy = location.getRadius();
    	                locData.direction = location.getDerect();
    	                //Log.d("loctest",String.format("before: lat: %f lon: %f", location.getLatitude(),location.getLongitude()));
    	               
    	                // GeoPoint p = CoordinateConver.fromGcjToBaidu(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)));
    	                //  Log.d("loctest",String.format("before: lat: %d lon: %d", p.getLatitudeE6(),p.getLongitudeE6()));
    	               
    	                myLocationOverlay.setData(locData);
    	                mMapView.refresh();
    	                //mMapController.setZoom(16);
    	                mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)), mHandler.obtainMessage());
    	     
    	                sb.append("\nradius : "); 
    	                sb.append(location.getRadius()); 
    	                
    	                if (location.getLocType() == BDLocation.TypeGpsLocation){ 
    	                    sb.append("\nspeed : "); 
    	                    sb.append(location.getSpeed()); 
    	                    sb.append("\nsatellite : "); 
    	                    sb.append(location.getSatelliteNumber()); 
    	                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){ 
    	                    sb.append("\naddr : "); 
    	                    sb.append(location.getAddrStr()); 
    	                } 
    	                sb.append("\nsdk version : "); 
    	                sb.append(mLocClient.getVersion()); 
    	                Log.v("bts:",sb.toString());
    	                //定时报告经纬度
    	                Updata tt=new Updata();
    	                tt.execute(sUinfo,Double.toString(dUsrLon),Double.toString(dUsrLat),sUsrTime);         
    			}

    			@Override
    			public void onReceivePoi(BDLocation location) {
    				// TODO Auto-generated method stub
    				//
    				
    			}	
            });
         
        mLocClient.start();
        
        
        mMapView.getController().setZoom(14);
        mMapView.getController().enableClick(true);
        mMapView.displayZoomControls(true);
        mMapListener = new MKMapViewListener() {
			
			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(wayclient.this,title,Toast.LENGTH_SHORT).show();
				}
			}
		};
	
		mMapView.regMapViewListener(ApplicationMain.getInstance().mBMapManager, mMapListener);
		
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
	    myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		mMapView.refresh();
    }
    
    class Updata extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			
			
			String sUsr=arg0[0];
			String sLon=arg0[1];
			String sLat=arg0[2];
			String sTime=arg0[3];
			//String sNote=arg0[3];
			Log.i("query result:", "ttts");
			if(this.bCheckUsrInfo(sUsr)==false){
				  List<NameValuePair> params = new ArrayList<NameValuePair>();
		          params.add(new BasicNameValuePair("username", sUsr));
		          params.add(new BasicNameValuePair("lon", sLon));
		          params.add(new BasicNameValuePair("lat", sLat));
		          params.add(new BasicNameValuePair("time", sTime));
		          params.add(new BasicNameValuePair("note", "ok"));
		          try{
		        	  // getting JSON Object
		              // Note that create product url accepts POST method
		         	   JSONObject json = JSONParser.makeHttpRequest(url_up,"POST", params);		
		         	   //String re_username = json.getString("username");
			   	   		//	String re_longitude = json.getString("lon");
			   	   		//	String re_latitude = json.getString("lat");
			   	   			
			   	   		//	Log.v("test:", "用戶名="+re_username);
			   	   		//	Log.v("test:", "經度="+re_longitude);
			   	   		//	Log.v("test:", "緯度="+re_latitude);
		   	   			
		   	            String message = json.getString(TAG_MESSAGE);
		   	            return message;
		            }catch(Exception e){
		                e.printStackTrace(); 
		                return "";          
		            }
		          
			}else{
				return "";  
			}
		}
		private boolean bCheckUsrInfo(String sUsr){
			
			Log.i("query result:", "adfasdf");
		   	HttpClient client = new DefaultHttpClient();
			StringBuilder builder = new StringBuilder();

			String ulrs=url_checkusr;
		    ulrs+="?username="+sUsr;
		    Log.i("query result:", ulrs);
			HttpGet myget = new HttpGet(ulrs);	
			
			try {
				
				HttpResponse response = client.execute(myget);
				BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent()));
				for (String s = reader.readLine(); s != null; s = reader.readLine()) {
					builder.append(s);
				}
				//String ss=builder.toString();
				Log.i("query result:",builder.toString());
				JSONObject jsonObject = new JSONObject(builder.toString());
				int re_success = jsonObject.getInt("success");
				if(re_success==1)
				{
					Log.i("数据存在:","1");
					return true;
				}
				else
				{
					Log.i("没有数据:","0");
					return false;
				}
			}catch (Exception e) {
				Log.i("test:", "false");
				e.printStackTrace();
				return false;
			}
		}
    	
    }
    
	@Override
	protected void onResume() {
	    ApplicationMain app = (ApplicationMain)this.getApplication();
		if (!app.m_bKeyRight) {
		    //TextView text = (TextView)findViewById(R.id.text_Info);
            Log.i("授权失败：","请在  ApplicationMain.java文件输入正确的授权Key！\r\n" +
                    "申请地址：http://dev.baidu.com/wiki/static/imap/key/");
            
		}
		super.onResume();
	}

	@Override
	// 建议在APP整体退出之前调用MapApi的destroy()函数，不要在每个activity的OnDestroy中调用，
    // 避免MapApi重复创建初始化，提高效率
	protected void onDestroy() {
	    ApplicationMain app = (ApplicationMain)this.getApplication();
		if (app.mBMapManager != null) {
			app.mBMapManager.destroy();
			app.mBMapManager = null;
		}
		super.onDestroy();
		System.exit(0);
	}
	
	ListView mListView = null;
    String mStrDemos[] = {
            "正在实时定位......"
            //"ReleaseEngine"
    };
    Class<?> mActivities[] = {
            wayclient.class
    };
    private void initMapView() {
        mMapView.setLongClickable(true);
        //mMapController.setMapClickEnable(true);
        //mMapView.setSatellite(false);
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	
	/**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return ;
            
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.direction = 2.0f;
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            //Log.d("loctest",String.format("before: lat: %f lon: %f", location.getLatitude(),location.getLongitude()));
           
            // GeoPoint p = CoordinateConver.fromGcjToBaidu(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)));
          //  Log.d("loctest",String.format("before: lat: %d lon: %d", p.getLatitudeE6(),p.getLongitudeE6()));
           
            myLocationOverlay.setData(locData);
            //mMapView.refresh();
            //mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)), mHandler.obtainMessage(1));
        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
    
    public class NotifyLister extends BDNotifyListener{
        public void onNotify(BDLocation mlocation, float distance) {
        }
    }
}